import requests as req;
import os;

def send(url,params):


    # UA伪装
    header = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36",
        "Mobile-User-Agent":"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Mobile Safari/537.36"
    }

    result = req.post(url=url,data=params,headers=header);

    return result;

if __name__ == '__main__':


    if(not os.path.exists("bug_file")):
        os.mkdir("bug_file");

    url = "https://fanyi.baidu.com/sug";
    key = input("请输入想要翻译的词:");
    params = {
        "kw":key
    }

    result = send(url,params);

    json = result.json();

    if json.get("errno") == 0:

        file_name = "爬虫-百度翻译-" + key + ".txt";
        with open("./bug_file/"+file_name, "w", encoding="utf-8") as wf:
            for item in json.get("data"):
                wf.write(str(item)+"\n");

        print(file_name, "翻译完毕!!");

    else:
        print("翻译失败!!",json.get("errno"));

